<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 9:39
 */
namespace app\admin\controller;

use app\admin\model\ProductModel;
use app\admin\model\ProClassifyModel;
use app\admin\model\ProAttrModel;
use think\Db;
class Product extends Base
{

    public function _initialize(){
        $this->pro = new ProductModel();
        $this->proclassify = new ProClassifyModel();
        $this->proattr = new ProAttrModel();
        parent::_initialize();
    }

    /*-----------------------< 产品列表 >-------------------------*/

    /**
     * [产品列表]
     */
    public function index(){
        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $whereOr = $this->seaWhereOr($param);
            $return['rows'] = $this->pro->getInfoByWhere(['delete_status'=>0],$whereOr,true,$offset,$limit,'id desc');
            $whereOr = $this->seaWhereOr($param);
            $return['total'] = $this->pro->getInfoByWhere(['delete_status'=>0],$whereOr,false);
            foreach($return['rows'] as $key =>$vo){
                $return['rows'][$key]['operate'] = showOperate($this->makeProListButton($vo['id']));
            }
            return json($return);
        }
        return $this->fetch();
    }

    /**
     * [添加产品]
     */
    public function productAdd(){
        if($this->request->isPost()){
            $param = input('post.');
            $param['attr_info'] = json_encode(array_merge(array_filter(explode('^',$param['attr_info']))));
            $param['create_uid'] = session('id');
            return $this->pro->productAdd($param);
        }
        return $this->fetch();
    }

    /**
     * [编辑产品]
     */
    public function productEdit(){
        $param = input('post.');
        $param['attr_info'] = json_encode(array_merge(array_filter(explode('^',$param['attr_info']))));
        $param['create_uid'] = session('id');
        return $this->pro->productEdit($param);
    }

    /**
     * [删除产品]
     */
    public function productDel(){
        $param = input('post.');
        $ids = explode(',',$param['ids']);
        return $this->pro->productDel($ids);
    }

    /**
     * [产品详情]
     */
    public function showPro(){
        $id = input('pro_id');
        $proInfo = $this->pro->getInfoByWhere(['id'=>$id],[],true)[0];
        $attr_info = $this->translateProAttrInfo($proInfo['attr_info']);
        $this->assign([
            'proInfo' => $proInfo,
            'attr_info' => $attr_info
        ]);
        return $this->fetch();
    }

    /**
     * [将产品的属性由json转换为标签]
     */
    public function translateProAttrInfo($json){
        $arr = json_decode($json);
        $return['code'] = '';
		$str = [];
        foreach($arr as $k => $v){
            $suffix[$k] = '<span class="badge" data-param="'.$v.'^"><i class="fa fa-remove"></i></span>';
            $return['code'] .= $v.'^';
            $s_arr = explode(",",$v);
            $price[$k] = '价格：<span style="color:#ed5565;font-weight:999;">'.explode("price:",$s_arr[sizeof($s_arr)-1])[1].'</span>';
            unset($s_arr[sizeof($s_arr)-1]);
            $str[$k] = '';
            foreach($s_arr as $ke => $va){
                $pid = explode('-',$va)[0];
                $sid = explode('-',$va)[1];
                $pinfo[$k][$ke] = DB::name('product_attr')->where('id',$pid)->value('name');
                $sinfo[$k][$ke] = DB::name('product_attr')->where('id',$sid)->value('name');
                $str[$k] .= $pinfo[$k][$ke].'：<span style="color:#ed5565;font-weight:999;">'.$sinfo[$k][$ke].'</span>，';
            }
            $str[$k] .= $price[$k] . $suffix[$k];
        }
        $return['translation'] = $str;
        return $return;
    }
    /*------------------------< 学校/专业 >------------------------*/

    /**
     * [学校/专业结构]
     */
    public function school (){
        if(request()->isAjax()){
            $school = $this->pro->getSchoolList();
            $school = getTree(objToArray($school), false);
            return json(msg(1, $school, 'ok'));
        }
        return $this->fetch();
    }

    /**
     * [添加学校/专业]
     */
    public function addSchool(){
        $param = input('post.');
        return $this->pro->addSchool($param);
    }

    /**
     * [编辑学校/专业]
     */
    public function editSchool(){
        $param = input('post.');
        return $this->pro->editSchool($param);
    }

    /**
     * [删除学校/专业]
     */
    public function delSchool(){
        $param = input('get.id');
        return $this->pro->delSchool($param);
    }

    /*------------------------< 产品分类 >------------------------*/

    /**
     * [产品分类]
     */
    public function classify(){
        if(request()->isAjax()){
            $classify = $this->proclassify->getClassifyList();
            $classify = getTree(objToArray($classify), false);
            return json(msg(1, $classify, 'ok'));
        }
        return $this->fetch();
    }

    /**
     * [添加分类]
     */
    public function addClassify(){
        $param = input('post.');
        $param['create_uid'] = session('id');
        return $this->proclassify->addClassify($param);
    }

    /**
     * [编辑分类]
     */
    public function editClassify(){
        $param = input('post.');
        return $this->proclassify->editClassify($param);
    }

    /**
     * [删除分类]
     */
    public function delClassify(){
        $param = input('get.id');
        return $this->proclassify->delClassify($param);
    }

    /*------------------------< 产品属性 >------------------------*/
    /**
     * [产品属性]
     */
    public function attr(){
        if(request()->isAjax()){
            $attr = $this->proattr->getAttrList();
            $attr = getTree(objToArray($attr), false);
            return json(msg(1, $attr, 'ok'));
        }
        return $this->fetch();
    }
    /**
     * [添加属性]
     */
    public function addAttr(){
        $param = input('post.');
        return $this->proattr->addAttr($param);
    }

    /**
     * [编辑属性]
     */
    public function editAttr(){
        $param = input('post.');
        return $this->proattr->editAttr($param);
    }

    /**
     * [删除属性]
     */
    public function delAttr(){
        $param = input('get.id');
        return $this->proattr->delAttr($param);
    }



    /**
     * [拼装产品配置操作按钮]
     */
    private function makeButton($id)
    {
        return [
            '编辑' => [
                'auth' => 'product/editproconfig',
                'href' => "javascript:editProConfig(" . $id . ")",
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [
                'auth' => 'product/delproconfig',
                'href' => "javascript:delProConfig(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];
    }

    /**
     * [拼装产品列表操作按钮]
     */
    private function makeProListButton($id)
    {
        return [
            '' => [
                'auth' => 'product/productdel',
                'href' => "javascript:delPro(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];
    }

    /**
     * [产品列表文本框搜索条件]
     */
    public function seaWhereOr($param){
        $this->pro->where(function($query)use($param){
            if($param['searchText']){
                $query->whereOr(['name'=>["like","%".$param['searchText']."%"]]);
                $query->whereOr(['school'=>["like","%".$param['searchText']."%"]]);
                $query->whereOr(['major'=>["like","%".$param['searchText']."%"]]);
                $query->whereOr(['c_name'=>["like","%".$param['searchText']."%"]]);
            }
        });
    }
}
